<template>
    <div class="news-container">

        <el-card>
            <div slot="header">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>新闻管理</el-breadcrumb-item>
                </el-breadcrumb>
            </div>

            <el-form :inline="true" ref="searchForm" :model="searchMap" label-width="80px">
                <el-form-item>
                    <el-input v-model="searchMap.title" size="small" placeholder="新闻标题"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-select v-model="searchMap.ncid" placeholder="新闻类别" size="small">
                        <el-option label="全部" value=""></el-option>
                        <el-option label="文明宣讲" value="1"></el-option>
                        <el-option label="旅游资讯" value="2"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-input v-model="searchMap.author" size="small" placeholder="发布者"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-date-picker v-model="searchMap.time" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" size="small">
                    </el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="mini" @click="selectNewsPage">
                        <i class="iconfont icon-search"></i>
                    </el-button>
                </el-form-item>
            </el-form>

            <div class="operaBtn">
                <el-button @click="hanleAddPre" type="primary" size="mini" class="el-icon-plus">新增</el-button>
                <el-button @click="handleDeleteListPre" type="danger" size="mini" class="el-icon-delete" :disabled="idList.length == 0 ? true : false">删除</el-button>
            </div>

            <el-table v-loading="editNewsLoading" ref="multipleTable" :data="newsArray" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="85">
                </el-table-column>
                <el-table-column prop="title" label="标题" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column prop="author.username" label="发布者">
                </el-table-column>
                <el-table-column prop="time" label="发布时间">
                </el-table-column>
                <el-table-column prop="newsCate.name" label="新闻类别" width="180">
                </el-table-column>

                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <el-button @click="editPre(scope.row,scope.$index)" type="primary" size="mini" class="el-icon-edit">编辑</el-button>
                        <el-button @click="deletePre(scope.row)" type="danger" size="mini" class="el-icon-delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 编辑对话框 -->
            <el-dialog title="新闻编辑" :visible.sync="editFormVisible">
                <el-form :model="editNewsForm" label-width="80px" label-position="left">
                    <el-form-item label="新闻标题">
                        <el-input  v-model="editNewsForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="发布者">
                        <el-input v-model="editNewsForm.author.username" disabled></el-input>
                    </el-form-item>

                    <el-form-item label="发布时间">
                        <el-date-picker v-model="editNewsForm.time" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" size="small">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="新闻内容">
                        <quill-editor
                            class="editor"
                            ref="quillEditor"
                            v-model="editNewsForm.content"
                            :options="editorOption"
                            @blur="onEditorBlur($event)"
                            @focus="onEditorFocus($event)"
                            @ready="onEditorReady($event)"
                        />   
                        <input type="file" @change="changeImage" id="upload" style="display:none;" />
                    </el-form-item>

                    <el-form-item label="新闻类别">
                        <el-select placeholder="选择分类" v-model="editNewsForm.newsCate.name">
                            <el-option label="文明宣讲" value="文明宣讲"></el-option>
                            <el-option label="旅游资讯" value="旅游资讯"></el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleEdit">确定</el-button>
                </div>
            </el-dialog>

            <!-- 新增对话框 -->
            <el-dialog title="新增新闻" :visible.sync="addFormVisible">
                <el-form :model="addForm" label-width="80px" label-position="left">
                    <el-form-item label="新闻标题">
                        <el-input  v-model="addForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="发布者">
                        <el-input v-model="addForm.author.username" disabled></el-input>
                    </el-form-item>

                    <el-form-item label="发布时间">
                        <el-date-picker v-model="addForm.time" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" size="small">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="新闻内容">
                        <quill-editor
                            class="editor"
                            ref="quillAddEditor"
                            v-model="addForm.content"
                            :options="editorAddOption"
                            @blur="onEditorBlur($event)"
                            @focus="onEditorFocus($event)"
                            @ready="onEditorReady($event)"
                        />   
                        <input type="file" @change="changeAddImage" id="uploadAdd" style="display:none;" />
                    </el-form-item>

                    <el-form-item label="新闻类别">
                        <el-select placeholder="选择分类" v-model="addForm.newsCate.ncid">
                            <el-option label="文明宣讲" value="1"></el-option>
                            <el-option label="旅游资讯" value="2"></el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancleAdd">取消</el-button>
                    <el-button type="primary" @click="handleAddNews">确定</el-button>
                </div>
            </el-dialog>


            <el-pagination
                class="pagination"
                background
                :pager-count="5"
                :page-size="5"
                layout="prev, pager, next"
                :current-page.sync="page"
                @current-change="pageChange"
                :total="newsCount">
            </el-pagination>

        </el-card>

    </div>
</template>

<script>
import { queryNewsPage,updateNews,selectNewsPage,getNewsCount,addNews,deleteNews,deleteNewsList } from '@/api/news'

import { uploadImg } from '@/api/uploadImage'
import { quillEditor, Quill } from 'vue-quill-editor'
import {container, ImageExtend} from 'quill-image-extend-module'
import ImageResize from "quill-image-resize-module"; // 引用
import { ImageDrop } from "quill-image-drop-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize); // 注册
Quill.register('modules/ImageExtend', ImageExtend)

export default {
    name: 'News',

    components:{ 
        quillEditor
    },

    data() {
        let newscate = {
            '文明宣讲':1,
            '旅游资讯':2,
        }

        const newscateMap = new Map(Object.entries(newscate))
        let result = JSON.parse(window.localStorage.getItem("result"));

        return {
            result,
            newscateMap,
            searchMap:{  //搜索条件
                title:null,
                ncid:null,
                author:null,
                time:null,
            },
            newsArray:[],//新闻的5条记录
            page:1,//当前所在页码
            newsCount:null,//新闻记录总条数
            editFormVisible: false,//编辑的对话框的开启与关闭
            editIndex:null,//编辑索引
            editNewsForm:{ //新闻编辑表单
                nid:null,
                title:null,
                time:null,
                content:null,
                newsCate:{ 
                    ncid:null,
                    name:null
                },
                author:{ 
                    uid:null,
                    username:null
                }
            },
            editNewsLoading:false,
            addFormVisible:false,
            addForm:{},//新闻新增表单
            idList:[],//批量删除的索引数组
            editorAddOption:{
                placeholder: '请输入文本...',
                theme: 'snow',
                modules: {

                    imageDrop: true, //图片拖拽
                    imageResize: {
                        displaySize: true
                    },

                    toolbar: {
                        container:container,
                        
                        handlers: {
                            image: function(value) {
                                if (value) {
                                    document.querySelector("#uploadAdd").click()  // 劫持原来的图片点击按钮事件
                                    
                                } else {
                                    this.quill.format('image', false)
                                }
                            }
                        }
                    }
                },
            },
            editorOption: {
                placeholder: '请输入文本...',
                theme: 'snow',
                modules: {

                    imageDrop: true, //图片拖拽
                    imageResize: {
                        displaySize: true
                    },

                    toolbar: {
                        container:container,
                        
                        handlers: {
                            image: function(value) {
                                if (value) {
                                    document.querySelector("#upload").click()  // 劫持原来的图片点击按钮事件
                                    
                                } else {
                                    this.quill.format('image', false)
                                }
                            }
                        }
                    }
                },
            },
        };
    },

    created(){ 
        this.addForm = { 
            ...this.editNewsForm,
            author:{
                uid:this.result.user.uid,
                username:this.result.user.username
            }
        }
    },

    mounted() {
        this.queryNewsPage()
        this.getNewsCount()
    },

    methods: {
        /**
         * 分页
         */
        pageChange(){ 
            this.editNewsLoading = true
            let data = {
                ...this.searchMap,
                'page':this.page
            }

            selectNewsPage(data).then(res => { 
                /**
                 * 查询成功后
                 * 1.更新新闻记录总数
                 * 2.更新数组
                 * 3.关闭load动画
                 */
                this.newsArray = res.data
                this.editNewsLoading = false
                this.getNewsCount()
            })
        },
        /**
         * 获取文物总数----带条件
         */
        getNewsCount(){
            /**
             * 在做删除操作时，我们需要首先拿到删除后的新闻总数，然后在进行后续操作
             * 但是在前端发送请求的时候是异步进行的
             * 这就要求我们要使用一种方法使得这种异步操作能够像同步操作一样的简单
             * 这里我们使用Promise来解决这一问题
             */
            return new Promise((resolve,reject) => { 
                let data = {
                    ...this.searchMap
                }
                getNewsCount(data).then(res => { 
                    this.newsCount = res.data
                    resolve(res)
                }).catch(err => { 
                    reject(new Error(err.statusText))
                })
            })

        },
        /**
         * 获取5条新闻记录
         */
        queryNewsPage(){ 
            let params = { 
                page:this.page
            }

            queryNewsPage(params).then(res => { 
                this.newsArray = res.data
            })
        },

        /**
         * 获取5条新闻记录---带条件
         */
        selectNewsPage(){ 
            this.page = 1
            this.editNewsLoading = true
            let data = {
                ...this.searchMap,
                'page':this.page
            }

            selectNewsPage(data).then(res => { 
                /**
                 * 查询成功后
                 * 1.更新新闻记录总数
                 * 2.更新数组
                 * 3.关闭load动画
                 */
                this.newsArray = res.data
                this.editNewsLoading = false
                this.getNewsCount()
            })



        },

        /**
         * 打开新增对话框
         */
        hanleAddPre(){ 
            this.addFormVisible = true
        },

        cancleAdd(){ 
            this.addFormVisible = false
            Object.keys(this.addForm).forEach(key => {this.addForm[key] = null})

            this.addForm.newsCate = { 
                name:null,
                ncid:null
            }

            this.addForm.author = {
                uid:this.result.user.uid,
                username:this.result.user.username
            }
        },

        /**
         * 处理新增新闻操作
         */
        handleAddNews(){ 
            let data = { 
                ...this.addForm
            }
            addNews(data).then(res => { 
                if(res.data == 1){ 
                    this.$message({ 
                        type:'success',
                        message:'新闻添加成功'
                    })
                    this.selectNewsPage()
                    this.addFormVisible = false
                    Object.keys(this.addForm).forEach(key => {this.addForm[key] = null})

                    this.addForm.newsCate = { 
                        name:null,
                        ncid:null
                    }

                    this.addForm.author = {
                        uid:this.result.user.uid,
                        username:this.result.user.username
                    }
                } else { 
                    this.$message({ 
                        type:'error',
                        message:'新闻添加失败'
                    })
                }
            })
        },

        /**
         * 打开编辑框
         */
        editPre(artifact,index){ 
            /**
             * 1.置editFormVisiable = true
             * 2.获取当前的索引，并赋值
             */
            this.editFormVisible = true
            this.editIndex = index
            /**
             * this.editNewsForm = artifact这种赋值方式Vue实际上是检测不到的，因为他只是简单的赋对象的地址
             * 这会产生一个bug，比如我打开编辑框，对信息进行修改，vue是双向绑定，于是他记录了这次修改
             * 关闭以后再次赋值，看到的是上次修改过的数据，这是不合理的
             * 这是因为对对象的直接赋值实际上是对地址的修改，每次的参数artifact都是未修改过的数据
             * 但是因为地址是一样的，vue检测不到，于是使得上次修改过的数据保存了下来，artifact未能成功赋值
             * 正确的做法是使用扩展运算符重新克隆对象
             */

            this.editNewsForm = { 
                ...artifact,
                newsCate:{ 
                    ...artifact.newsCate
                },
                author:{ 
                    ...artifact.author
                }
            }
        },

        /**
         * 编辑处理
         */
        handleEdit(){ 
            this.editNewsForm.newsCate.ncid = this.newscateMap.get(this.editNewsForm.newsCate.name)

            let data = this.editNewsForm

            updateNews(data).then(res => { 
                console.log("res=",res)
                this.newsArray.splice(this.editIndex,1,data)
                this.$message({ 
                    type:'success',
                    message:'编辑成功'
                })
            })

            this.editFormVisible = false
        },


        /**
         * 批量删除前处理
         */
        handleDeleteListPre(){ 
            this.$confirm('你确定要删除这些新闻吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => { 
                this.handleDeleteList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        /**
         * 批量删除
         */
        handleDeleteList() { 

            let idArray = "";

            this.idList.forEach(item => { 
                idArray += item.nid + ","
            })

            let params = { 
                'idList':idArray
            }

            deleteNewsList(params).then(res => { 
                /**
                 * 删除成功要做这几件事
                 * 1.更新newsCount，总页码 ----- newsCount % 5 == 0 ? newsCount / 5 : newsCount / 5 + 1
                 * 2.新的总页码和当前所在页码作比较，如果新的页码比当前所在页码要小，则当前所在页码-1
                 * 3.更新
                 */
                this.getNewsCount().then(() => { 
                    let newPage = this.newsCount % 5 == 0 ? this.newsCount / 5 : this.newsCount / 5 + 1
                    console.log("newPage = ",newPage)
                    let page = this.page != 1 && this.page > newPage ? page - 1 : this.page
                    this.page = page
                    console.log("this.page = ",this.page)

                    this.pageChange()
                    /**
                     * 更新
                     */
                    
                    this.$message({ 
                        type:'success',
                        message:'删除成功'
                    })
                })
            
            })

        },

        /**
         * 删除前处理
         */
        deletePre(news){ 
            this.$confirm('你确定要删除此项新闻记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => { 
                this.handleDelete(news.nid)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        /**
         * 删除处理
         */
        handleDelete(nid){ 
            let params = { 
                nid
            }

            deleteNews(params).then(res => { 
                /**
                 * 删除成功要做这几件事
                 * 1.更新newsCount，总页码 ----- newsCount % 5 == 0 ? newsCount / 5 : newsCount / 5 + 1
                 * 2.新的总页码和当前所在页码作比较，如果新的页码比当前所在页码要小，则当前所在页码-1
                 * 3.更新
                 */
                this.getNewsCount().then(() => { 
                    let newPage = this.newsCount % 5 == 0 ? this.newsCount / 5 : this.newsCount / 5 + 1
                    let page = this.page != 1 && this.page > newPage ? page - 1 : this.page
                    this.page = page
                    /**
                     * 更新
                     */
                    this.pageChange()
                    this.$message({ 
                        type:'success',
                        message:'删除成功'
                    })
                })

            })
        },




        handleSelectionChange(val){ 
            this.idList = [...val]
            console.log("idlist = ",this.idList)
        },

        onEditorBlur(quill) {
            console.log('editor blur!', quill)
        },
        //获得焦点事件
        onEditorFocus(quill) {
            console.log('editor focus!', quill)
        },
        // 准备富文本编辑器
        onEditorReady(quill) {
            console.log('editor ready!', quill)
        },

        changeAddImage(e){ 
            let file = e.target.files[0]
            const formData = new FormData()
            formData.append('file', file)

            uploadImg(formData).then(res => {
                console.log("quill上传成功！！！！") 
                let quill = this.$refs.quillAddEditor.quill
                let length = quill.getSelection().index
                console.log("光标位置",length)

                let fileUrl = res.data
                quill.insertEmbed(length, 'image', fileUrl)
                quill.setSelection(length + 1)//光标后移一位

            }).catch(err => {

            })
        },

        /**
         * 当富文本编辑器选中图片后执行上传图片操作
         */
        changeImage(e){ 
            console.log("quill",this.$refs.quillEditor.quill)
            console.log("quill上传文件",e)

            let file = e.target.files[0]
            const formData = new FormData()
            formData.append('file', file)

            uploadImg(formData).then(res => {
                console.log("quill上传成功！！！！") 
                let quill = this.$refs.quillEditor.quill
                let length = quill.getSelection().index
                console.log("光标位置",length)

                let fileUrl = res.data
                quill.insertEmbed(length, 'image', fileUrl)
                quill.setSelection(length + 1)//光标后移一位

            }).catch(err => {

            })

        },
    },
};
</script>

<style scoped>
.news-container
{
    margin: 20px 30px;
    min-width: 1275px;
}

.pagination{ 
    margin-top: 30px;
}
</style>